<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="记录编号" prop="recordCode">
        <el-input v-model="queryParams.recordCode" placeholder="请输入记录编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="仓库名称" prop="warehouseName">
        <el-input v-model="queryParams.warehouseName" placeholder="请输入仓库名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="物料编码" prop="materialCode">
        <el-input v-model="queryParams.materialCode" placeholder="请输入物料编码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="操作类型" prop="operationType">
        <el-select v-model="queryParams.operationType" placeholder="请选择操作类型" clearable>
          <el-option label="入库" value="入库" />
          <el-option label="出库" value="出库" />
          <el-option label="调拨" value="调拨" />
        </el-select>
      </el-form-item>
      <el-form-item label="记录类型" prop="recordType">
        <el-select v-model="queryParams.recordType" placeholder="请选择记录类型" clearable>
          <el-option label="入库" value="入库" />
          <el-option label="出库" value="出库" />
          <el-option label="调拨" value="调拨" />
          <el-option label="盘点" value="盘点" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['inventory:record:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['inventory:record:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['inventory:record:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['inventory:record:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录ID" align="center" prop="recordId" />
      <el-table-column label="记录编号" align="center" prop="recordCode" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="物料编码" align="center" prop="materialCode" />
      <el-table-column label="物料名称" align="center" prop="materialName" />
      <el-table-column label="批次号" align="center" prop="batchCode" />
      <el-table-column label="操作类型" align="center" prop="operationType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.operationType == '入库'" type="success">入库</el-tag>
          <el-tag v-else-if="scope.row.operationType == '出库'" type="danger">出库</el-tag>
          <el-tag v-else type="warning">调拨</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作数量" align="center" prop="quantity" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="操作人员" align="center" prop="operatorName" />
      <!-- 修改操作日期字段 -->
      <el-table-column label="操作日期" align="center" prop="operationTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <!-- 修改关联单号字段 -->
      <el-table-column label="关联单号" align="center" prop="relatedOrderCode" />
      <el-table-column label="记录类型" align="center" prop="recordType" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['inventory:record:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['inventory:record:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改库存记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="记录编号" prop="recordCode">
              <el-input v-model="form.recordCode" placeholder="请输入记录编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作类型" prop="operationType">
              <el-select v-model="form.operationType" placeholder="请选择操作类型" style="width: 100%">
                <el-option label="入库" value="入库" />
                <el-option label="出库" value="出库" />
                <el-option label="调拨" value="调拨" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="记录类型" prop="recordType">
              <el-select v-model="form.recordType" placeholder="请选择记录类型" style="width: 100%">
                <el-option label="入库" value="入库" />
                <el-option label="出库" value="出库" />
                <el-option label="调拨" value="调拨" />
                <el-option label="盘点" value="盘点" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{
                  dict.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 仓库和物料信息 -->
        <el-divider content-position="left">仓库和物料信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="请选择仓库" @change="handleWarehouseChange"
                style="width: 100%">
                <el-option v-for="warehouse in warehouseList" :key="warehouse.warehouseId"
                  :label="warehouse.warehouseName" :value="warehouse.warehouseId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料信息" prop="materialId">
              <el-select v-model="form.materialId" placeholder="请选择物料" @change="handleMaterialChange" clearable
                filterable style="width: 100%">
                <el-option v-for="material in materialList" :key="material.materialId"
                  :label="`${material.materialCode} - ${material.materialName}`" :value="material.materialId">
                  <span style="float: left">{{ material.materialCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ material.materialName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="form.materialCode" placeholder="物料编码（自动填充）" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="物料名称（自动填充）" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 数量和批次信息 -->
        <el-divider content-position="left">数量和批次信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="操作数量" prop="quantity">
              <el-input v-model="form.quantity" placeholder="请输入操作数量" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次号" prop="batchCode">
              <el-input v-model="form.batchCode" placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 操作信息 -->
        <el-divider content-position="left">操作信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 修改操作日期字段名 -->
            <el-form-item label="操作日期" prop="operationTime">
              <el-date-picker clearable v-model="form.operationTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="操作日期（自动填充）" :disabled="true" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作人员" prop="operatorName">
              <el-input v-model="form.operatorName" placeholder="操作人员（自动填充）" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 关联信息 -->
        <el-divider content-position="left">关联信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="关联订单号" prop="relatedOrderId">
              <el-select v-model="form.relatedOrderId" placeholder="请选择关联订单" clearable style="width: 100%"
                @change="handleOrderChange">
                <el-option v-for="order in workOrderList" :key="order.orderId" :label="order.orderCode"
                  :value="order.orderId">
                  <span style="float: left">{{ order.orderCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ order.orderName || '工单' }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注信息 -->
        <el-divider content-position="left">备注信息</el-divider>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInventoryRecord, getInventoryRecord, delInventoryRecord, addInventoryRecord, updateInventoryRecord, checkRecordCodeUnique } from "@/api/mes/inventory/inventoryRecord";
import { listActive as listActiveWarehouse } from "@/api/mes/inventory/warehouse";
import { listMaterial } from "@/api/mes/basic/material";
import { listWorkOrder } from "@/api/mes/production/workorder"; // 添加工单API

export default {
  name: "InventoryRecord",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存记录表格数据
      recordList: [],
      // 仓库列表
      warehouseList: [],
      // 物料列表
      materialList: [],
      // 工单列表
      workOrderList: [], // 添加工单列表
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        recordCode: null,
        warehouseName: null,
        materialCode: null,
        materialName: null,
        operationType: null,
        recordType: null,
        status: null
      },
      // 表单参数
      form: {
        operationTime: null,
      },
      // 表单校验
      rules: {
        recordCode: [
          { required: true, message: "记录编号不能为空", trigger: "blur" },
          { validator: this.validateRecordCode, trigger: "blur" }
        ],
        warehouseId: [
          { required: true, message: "仓库ID不能为空", trigger: "blur" }
        ],
        materialId: [
          { required: true, message: "物料ID不能为空", trigger: "blur" }
        ],
        operationType: [
          { required: true, message: "操作类型不能为空", trigger: "change" }
        ],
        quantity: [
          { required: true, message: "操作数量不能为空", trigger: "blur" }
        ],
        operationTime: [
          { required: true, message: "操作时间不能为空", trigger: "blur" }
        ],
        recordType: [
          { required: true, message: "记录类型不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getWarehouseList();
    this.getMaterialList();
    this.getWorkOrderList(); // 添加获取工单列表
  },
  methods: {
    /** 查询库存记录列表 */
    getList() {
      this.loading = true;
      listInventoryRecord(this.queryParams).then(response => {
        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recordId: null,
        recordCode: null,
        warehouseId: null,
        warehouseName: null,
        materialId: null,
        materialCode: null,
        materialName: null,
        batchCode: null,
        operationType: null,
        quantity: null,
        // 修改这行：将 operationDate 改为 operationTime
        operationTime: this.getCurrentDate(),
        unit: null,
        operatorId: this.$store.getters.id,
        operatorName: this.$store.getters.name,
        relatedOrderId: null,
        relatedOrderCode: null,
        status: "0",
        operator: null,
        recordType: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recordId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库存记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recordId = row.recordId || this.ids
      getInventoryRecord(recordId).then(response => {
        this.form = response.data;
        this.originalRecordCode = response.data.recordCode; // 保存原始编码
        this.open = true;
        this.title = "修改库存记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.recordId != null) {
            updateInventoryRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInventoryRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordIds = row.recordId || this.ids;
      this.$modal.confirm('是否确认删除库存记录编号为"' + recordIds + '"的数据项？').then(function () {
        return delInventoryRecord(recordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('inventory/record/export', {
        ...this.queryParams
      }, `inventoryRecord_${new Date().getTime()}.xlsx`)
    },
    /** 校验记录编号唯一性 */
    validateRecordCode(rule, value, callback) {
      if (value) {
        // 编辑时排除当前记录
        const params = {
          recordCode: value,
          recordId: this.form.recordId // 传递当前记录ID
        };
        checkRecordCodeUnique(params).then(response => {
          // 如果是编辑模式且编码未变化，直接通过验证
          if (this.form.recordId && this.originalRecordCode === value) {
            callback();
            return;
          }
          if (response.code === 200) {
            callback();
          } else {
            callback(new Error(response.msg || '记录编号已存在'));
          }
        }).catch(() => {
          callback(new Error('验证记录编号时发生错误'));
        });
      } else {
        callback();
      }
    },

    /** 获取仓库列表 */
    getWarehouseList() {
      listActiveWarehouse().then(response => {
        this.warehouseList = response.data;
      });
    },

    /** 处理仓库选择变化 */
    handleWarehouseChange(warehouseId) {
      const selectedWarehouse = this.warehouseList.find(warehouse => warehouse.warehouseId === warehouseId);
      if (selectedWarehouse) {
        this.form.warehouseName = selectedWarehouse.warehouseName;
      } else {
        this.form.warehouseName = '';
      }
    },

    /** 获取物料列表 */
    getMaterialList() {
      listMaterial({}).then(response => {
        this.materialList = response.rows || response.data || [];
      });
    },

    /** 处理物料选择变化 */
    handleMaterialChange(materialId) {
      const selectedMaterial = this.materialList.find(material => material.materialId === materialId);
      if (selectedMaterial) {
        this.form.materialCode = selectedMaterial.materialCode;
        this.form.materialName = selectedMaterial.materialName;
      } else {
        this.form.materialCode = '';
        this.form.materialName = '';
      }
    },
    /** 获取工单列表 */
    getWorkOrderList() {
      listWorkOrder({ status: '1' }).then(response => {
        this.workOrderList = response.rows || [];
      });
    },

    /** 处理订单选择变化 */
    handleOrderChange(orderId) {
      if (orderId) {
        const selectedOrder = this.workOrderList.find(order => order.orderId === orderId);
        if (selectedOrder) {
          this.form.relatedOrderCode = selectedOrder.orderCode;
        }
      } else {
        this.form.relatedOrderCode = null;
      };
    },
    /** 获取当前日期 */
    getCurrentDate() {
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0');
      const day = String(today.getDate()).padStart(2, '0');
      const hours = String(today.getHours()).padStart(2, '0');
      const minutes = String(today.getMinutes()).padStart(2, '0');
      const seconds = String(today.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  }
};
</script>